#!/usr/bin/env python3
"""
供应链业务数据分析示例
展示如何使用BusinessDatasetInterface进行实际业务分析
"""

from business_dataset_interface import BusinessDatasetInterface
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

def demand_forecasting_analysis():
    """需求预测分析示例"""
    print("\n=== 需求预测分析示例 ===")
    
    # 初始化数据接口
    data_interface = BusinessDatasetInterface()
    
    try:
        # 加载需求预测数据
        df = data_interface.load_dataset('plan', '需求预测数据')
        
        # 数据预处理
        df['Date'] = pd.to_datetime(df['Date'])
        df['Year'] = df['Date'].dt.year
        df['Month'] = df['Date'].dt.month
        df['Quarter'] = df['Date'].dt.quarter
        
        print(f"\n📊 数据集概览:")
        print(f"   时间范围: {df['Date'].min()} 至 {df['Date'].max()}")
        print(f"   产品数量: {df['Product_Code'].nunique()}")
        print(f"   仓库数量: {df['Warehouse'].nunique()}")
        print(f"   产品类别: {df['Product_Category'].nunique()}")
        print(f"   总需求量: {df['Order_Demand'].sum():,}")
        
        # 1. 时间趋势分析
        print("\n📈 时间趋势分析")
        monthly_demand = df.groupby(['Year', 'Month'])['Order_Demand'].sum().reset_index()
        monthly_demand['Date'] = pd.to_datetime(monthly_demand[['Year', 'Month']].assign(day=1))
        
        plt.figure(figsize=(15, 6))
        plt.subplot(1, 2, 1)
        plt.plot(monthly_demand['Date'], monthly_demand['Order_Demand'])
        plt.title('月度需求趋势')
        plt.xlabel('时间')
        plt.ylabel('需求量')
        plt.xticks(rotation=45)
        
        # 2. 季节性分析
        seasonal_demand = df.groupby('Month')['Order_Demand'].mean()
        plt.subplot(1, 2, 2)
        seasonal_demand.plot(kind='bar')
        plt.title('月度平均需求（季节性）')
        plt.xlabel('月份')
        plt.ylabel('平均需求量')
        plt.xticks(rotation=0)
        
        plt.tight_layout()
        plt.savefig('需求趋势分析.png', dpi=300, bbox_inches='tight')
        plt.show()
        
        # 3. 产品分析
        print("\n🏷️ 产品分析")
        top_products = df.groupby('Product_Code')['Order_Demand'].sum().sort_values(ascending=False).head(10)
        print("需求量前10的产品:")
        for i, (product, demand) in enumerate(top_products.items(), 1):
            print(f"   {i}. {product}: {demand:,}")
        
        # 4. 仓库分析
        print("\n🏭 仓库分析")
        warehouse_performance = df.groupby('Warehouse').agg({
            'Order_Demand': ['sum', 'mean', 'count'],
            'Product_Code': 'nunique'
        }).round(2)
        warehouse_performance.columns = ['总需求', '平均需求', '订单数', '产品种类']
        print(warehouse_performance.sort_values('总需求', ascending=False))
        
        # 5. 类别分析
        print("\n📦 产品类别分析")
        category_analysis = df.groupby('Product_Category').agg({
            'Order_Demand': ['sum', 'mean'],
            'Product_Code': 'nunique'
        }).round(2)
        category_analysis.columns = ['总需求', '平均需求', '产品数量']
        category_analysis['需求占比'] = (category_analysis['总需求'] / category_analysis['总需求'].sum() * 100).round(2)
        print(category_analysis.sort_values('总需求', ascending=False).head(10))
        
        return df
        
    except Exception as e:
        print(f"需求预测分析失败: {e}")
        return None

def supply_chain_analysis():
    """供应链综合分析示例"""
    print("\n=== 供应链综合分析示例 ===")
    
    data_interface = BusinessDatasetInterface()
    
    try:
        # 加载DataCo智能供应链数据
        df = data_interface.load_dataset('comprehensive', 'DataCo智能供应链')
        
        print(f"\n📊 数据集概览:")
        print(f"   订单数量: {len(df):,}")
        print(f"   列数: {len(df.columns)}")
        print(f"   主要列: {', '.join(df.columns[:10].tolist())}...")
        
        # 检查关键业务指标
        key_metrics = []
        if 'Benefit per order' in df.columns:
            key_metrics.append('Benefit per order')
        if 'Sales per customer' in df.columns:
            key_metrics.append('Sales per customer')
        if 'Days for shipping (real)' in df.columns:
            key_metrics.append('Days for shipping (real)')
        if 'Days for shipment (scheduled)' in df.columns:
            key_metrics.append('Days for shipment (scheduled)')
        
        if key_metrics:
            print(f"\n📈 关键业务指标统计:")
            for metric in key_metrics:
                if df[metric].dtype in ['int64', 'float64']:
                    print(f"   {metric}:")
                    print(f"     平均值: {df[metric].mean():.2f}")
                    print(f"     中位数: {df[metric].median():.2f}")
                    print(f"     标准差: {df[metric].std():.2f}")
        
        # 分析配送绩效
        if 'Days for shipping (real)' in df.columns and 'Days for shipment (scheduled)' in df.columns:
            print("\n🚚 配送绩效分析")
            df['Delivery_Delay'] = df['Days for shipping (real)'] - df['Days for shipment (scheduled)']
            
            on_time_rate = (df['Delivery_Delay'] <= 0).mean() * 100
            avg_delay = df['Delivery_Delay'].mean()
            
            print(f"   准时交付率: {on_time_rate:.1f}%")
            print(f"   平均延迟: {avg_delay:.1f}天")
            
            # 延迟分布
            plt.figure(figsize=(12, 4))
            plt.subplot(1, 2, 1)
            df['Delivery_Delay'].hist(bins=50, alpha=0.7)
            plt.title('配送延迟分布')
            plt.xlabel('延迟天数')
            plt.ylabel('频次')
            
            plt.subplot(1, 2, 2)
            delay_categories = pd.cut(df['Delivery_Delay'], 
                                    bins=[-np.inf, -1, 0, 1, 3, 7, np.inf],
                                    labels=['提前2天+', '提前1天', '准时', '延迟1天', '延迟2-7天', '延迟7天+'])
            delay_categories.value_counts().plot(kind='bar')
            plt.title('配送绩效分类')
            plt.xlabel('配送状态')
            plt.ylabel('订单数量')
            plt.xticks(rotation=45)
            
            plt.tight_layout()
            plt.savefig('配送绩效分析.png', dpi=300, bbox_inches='tight')
            plt.show()
        
        return df
        
    except Exception as e:
        print(f"供应链综合分析失败: {e}")
        return None

def delivery_performance_analysis():
    """交付绩效分析示例"""
    print("\n=== 交付绩效分析示例 ===")
    
    data_interface = BusinessDatasetInterface()
    
    try:
        # 加载交付数据
        df = data_interface.load_dataset('deliver', '交付数据')
        
        print(f"\n📊 交付数据概览:")
        print(f"   订单数量: {len(df):,}")
        print(f"   列数: {len(df.columns)}")
        
        # 准时交付分析
        if 'Reached.on.Time_Y.N' in df.columns:
            print("\n⏰ 准时交付分析")
            ontime_stats = df['Reached.on.Time_Y.N'].value_counts()
            ontime_rate = (ontime_stats.get(1, 0) / len(df)) * 100
            
            print(f"   准时交付率: {ontime_rate:.1f}%")
            print(f"   准时订单: {ontime_stats.get(1, 0):,}")
            print(f"   延迟订单: {ontime_stats.get(0, 0):,}")
        
        # 运输方式分析
        if 'Mode_of_Shipment' in df.columns:
            print("\n🚛 运输方式分析")
            shipment_mode = df['Mode_of_Shipment'].value_counts()
            print(shipment_mode)
            
            # 各运输方式的准时率
            if 'Reached.on.Time_Y.N' in df.columns:
                mode_performance = df.groupby('Mode_of_Shipment')['Reached.on.Time_Y.N'].agg(['count', 'mean']).round(3)
                mode_performance.columns = ['订单数', '准时率']
                mode_performance['准时率'] = mode_performance['准时率'] * 100
                print("\n各运输方式绩效:")
                print(mode_performance.sort_values('准时率', ascending=False))
        
        # 客户服务分析
        if 'Customer_care_calls' in df.columns:
            print("\n📞 客户服务分析")
            care_calls = df['Customer_care_calls'].value_counts().sort_index()
            print(f"   平均客服电话: {df['Customer_care_calls'].mean():.2f}次")
            print(f"   客服电话分布:")
            for calls, count in care_calls.items():
                print(f"     {calls}次: {count:,}订单 ({count/len(df)*100:.1f}%)")
        
        # 仓库区域分析
        if 'Warehouse_block' in df.columns:
            print("\n🏭 仓库区域分析")
            warehouse_performance = df.groupby('Warehouse_block').agg({
                'Reached.on.Time_Y.N': ['count', 'mean'] if 'Reached.on.Time_Y.N' in df.columns else ['count'],
                'Customer_care_calls': 'mean' if 'Customer_care_calls' in df.columns else 'count'
            }).round(3)
            
            if 'Reached.on.Time_Y.N' in df.columns:
                warehouse_performance.columns = ['订单数', '准时率', '平均客服电话']
                warehouse_performance['准时率'] = warehouse_performance['准时率'] * 100
            
            print(warehouse_performance.sort_values('订单数', ascending=False))
        
        return df
        
    except Exception as e:
        print(f"交付绩效分析失败: {e}")
        return None

def generate_business_insights():
    """生成业务洞察报告"""
    print("\n=== 生成业务洞察报告 ===")
    
    insights = {
        "report_date": datetime.now().isoformat(),
        "analysis_summary": {
            "datasets_analyzed": [],
            "key_findings": [],
            "recommendations": []
        }
    }
    
    # 执行各项分析
    demand_df = demand_forecasting_analysis()
    if demand_df is not None:
        insights["analysis_summary"]["datasets_analyzed"].append("需求预测数据")
        insights["analysis_summary"]["key_findings"].append(f"分析了{len(demand_df):,}条需求记录")
        insights["analysis_summary"]["recommendations"].append("基于历史需求数据优化库存规划")
    
    supply_df = supply_chain_analysis()
    if supply_df is not None:
        insights["analysis_summary"]["datasets_analyzed"].append("DataCo智能供应链")
        insights["analysis_summary"]["key_findings"].append(f"分析了{len(supply_df):,}条供应链记录")
        insights["analysis_summary"]["recommendations"].append("优化配送流程以提高准时交付率")
    
    delivery_df = delivery_performance_analysis()
    if delivery_df is not None:
        insights["analysis_summary"]["datasets_analyzed"].append("交付数据")
        insights["analysis_summary"]["key_findings"].append(f"分析了{len(delivery_df):,}条交付记录")
        insights["analysis_summary"]["recommendations"].append("改进客户服务流程以减少客服电话")
    
    # 保存洞察报告
    import json
    with open('Business_Insights_Report.json', 'w', encoding='utf-8') as f:
        json.dump(insights, f, ensure_ascii=False, indent=2, default=str)
    
    print(f"\n📋 业务洞察报告已生成: Business_Insights_Report.json")
    print(f"   分析数据集: {len(insights['analysis_summary']['datasets_analyzed'])}个")
    print(f"   关键发现: {len(insights['analysis_summary']['key_findings'])}项")
    print(f"   业务建议: {len(insights['analysis_summary']['recommendations'])}条")
    
    return insights

def main():
    """主函数"""
    print("供应链业务数据分析示例")
    print("基于已下载的Kaggle数据集进行实际业务分析")
    
    try:
        # 生成综合业务洞察
        insights = generate_business_insights()
        
        print("\n✅ 业务分析完成！")
        print("\n生成的文件:")
        print("  📊 需求趋势分析.png - 需求预测可视化")
        print("  🚚 配送绩效分析.png - 配送绩效可视化")
        print("  📋 Business_Insights_Report.json - 业务洞察报告")
        
        print("\n💡 使用建议:")
        print("  1. 查看生成的图表了解业务趋势")
        print("  2. 阅读洞察报告获取业务建议")
        print("  3. 基于分析结果制定业务策略")
        print("  4. 定期运行分析以监控业务变化")
        
    except Exception as e:
        print(f"分析过程出错: {e}")
        print("请确保数据集已正确下载并可访问")

if __name__ == "__main__":
    main()